<template>
  <common-layout>
    <h1 style="text-align:center; color:rgb(202, 56, 96); font-size: 36px; font-weight: bolder">UENC辅助管理软件</h1>
    <div class="loginBox">
      <div class="top">
        <div class="header">
          <img alt="logo" class="logo" src="@/assets/img/logo.png" />
          <span class="title">{{systemName}}</span>
        </div>
        <!-- <div class="desc">Ant Design 是西湖区最具影响力的 Web 设计规范</div> -->
      </div>
      <div class="login">
        <a-form @submit="onSubmit" :form="form" v-if="pageStatus == '登录'">
          <a-tabs size="large" :tabBarStyle="{textAlign: 'center'}" style="padding: 0 2px;">
            <a-tab-pane tab="账户密码登录" key="1">
              <a-alert type="error" :closable="true" v-if="error" :message="error" @close='onClose' showIcon
                style="margin-bottom: 24px;" />
              <a-form-item>
                <a-input autocomplete="autocomplete" size="large" placeholder="请输入账户名"
                  v-decorator="['name', {rules: [{ required: true, message: '请输入账户名', whitespace: true}]}]">
                  <a-icon slot="prefix" type="user" />
                </a-input>
              </a-form-item>
              <a-form-item>
                <a-input size="large" placeholder="请输入密码" autocomplete="autocomplete" type="password"
                  v-decorator="['password', {rules: [{ required: true, message: '请输入密码', whitespace: true}]}]">
                  <a-icon slot="prefix" type="lock" />
                </a-input>
              </a-form-item>
            </a-tab-pane>
          </a-tabs>
          <div>
            <a-checkbox :checked="true">自动登录</a-checkbox>
            <a style="float: right" @click="pageStatus = '忘记'">忘记密码</a>
          </div>
          <a-form-item>
            <a-button :loading="logging" style="width: 100%;margin-top: 24px" size="large" htmlType="submit"
              type="primary">登录</a-button>
          </a-form-item>
          <div>
            <!-- 其他登录方式
            <a-icon class="icon" type="alipay-circle" />
            <a-icon class="icon" type="taobao-circle" />
            <a-icon class="icon" type="weibo-circle" /> -->
            <a style="float: right; margin-top: -10px" @click="pageStatus = '注册'">注册账户</a>
          </div>
        </a-form>

        <a-form-model v-else-if="pageStatus == '注册'" layout="horizontal">
          <a-tabs size="large" :tabBarStyle="{textAlign: 'center'}" style="padding: 0 2px;">
            <a-tab-pane tab="免费注册" key="1">
              <a-alert type="error" :closable="true" v-if="error" :message="error" @close='onClose' showIcon
                style="margin-bottom: 24px;" />
              <a-form-model-item>
                <a-input placeholder="用户名" v-model="regForm.username" autocomplete="autocomplete" size="large">
                  <a-icon slot="prefix" type="user" />
                </a-input>
              </a-form-model-item>
              <a-form-model-item>
                <a-input placeholder="密码" v-model="regForm.password" autocomplete="autocomplete" size="large">
                  <a-icon slot="prefix" type="lock" />
                </a-input>
              </a-form-model-item>
              <a-form-model-item>
                <a-input placeholder="确认密码" v-model="regForm.checkpassword" autocomplete="autocomplete" size="large">
                  <a-icon slot="prefix" type="lock" />
                </a-input>
              </a-form-model-item>
              <a-form-model-item>
                <a-input placeholder="手机号" v-model="regForm.tel" autocomplete="autocomplete" size="large">
                  <a-icon slot="prefix" type="phone" />
                </a-input>
              </a-form-model-item>
              <a-form-model-item>
                <a-row :gutter="20" type="flex" justify="space-between">
                  <a-col :span="16">
                    <a-input placeholder="验证码" v-model="regForm.phoneCode" autocomplete="autocomplete" size="large">
                      <a-icon slot="prefix" type="mail" />
                    </a-input>
                  </a-col>
                  <a-col :span="8">
                    <a-button :disabled="disabledReg" size="large" style="margin-left: -15px" @click="getCode('注册')">{{ regMsg }}</a-button>
                  </a-col>
                </a-row>
              </a-form-model-item>
              <a-form-model-item :wrapperCol="{ span: 24, offset: 1 }">
                <a-button style="width: 43%;" type="primary" @click="toRegister">注册</a-button>
                <a-button style="width: 43%; margin-left: 20px;" @click="pageStatus = '登录'">取消</a-button>
              </a-form-model-item>
            </a-tab-pane>
          </a-tabs>
        </a-form-model>

        <a-form-model v-else-if="pageStatus == '忘记'" layout="horizontal">
          <a-tabs size="large" :tabBarStyle="{textAlign: 'center'}" style="padding: 0 2px;">
            <a-tab-pane tab="忘了密码" key="1">
              <a-alert type="error" :closable="true" v-if="error" :message="error" @close='onClose' showIcon
                style="margin-bottom: 24px;" />
              <a-form-model-item>
                <a-input placeholder="密码" v-model="forgetForm.password" autocomplete="autocomplete" size="large">
                  <a-icon slot="prefix" type="lock" />
                </a-input>
              </a-form-model-item>
              <a-form-model-item>
                <a-input placeholder="手机号" v-model="forgetForm.tel" autocomplete="autocomplete" size="large">
                  <a-icon slot="prefix" type="phone" />
                </a-input>
              </a-form-model-item>
              <a-form-model-item>
                <a-row :gutter="20" type="flex" justify="space-between">
                  <a-col :span="16">
                    <a-input placeholder="验证码" v-model="forgetForm.phoneCode" autocomplete="autocomplete" size="large">
                      <a-icon slot="prefix" type="mail" />
                    </a-input>
                  </a-col>
                  <a-col :span="8">
                    <a-button :disabled="disabledCodeBtn" size="large" style="margin-left: -15px" @click="getCode('修改密码')">{{ forgetMsg }}</a-button>
                  </a-col>
                </a-row>
              </a-form-model-item>
              <a-form-model-item>
                <a-button style="width: 100%;" :loading="resendStatus" size="large" @click="resend()" type="primary">重置</a-button>
              </a-form-model-item>
            </a-tab-pane>
          </a-tabs>
        </a-form-model>
      </div>
    </div>
  </common-layout>
</template>

<script>
  import CommonLayout from '@/layouts/CommonLayout'
  import {
    login,
    getPhoneCode,
    updatePwd,
    register
  } from '@/services/user'
  import {
    setAuthorization
  } from '@/utils/request'
  import {
    loadRoutes
  } from '@/utils/routerUtil'
  import {
    mapMutations
  } from 'vuex'

  export default {
    name: 'Login',
    components: {
      CommonLayout
    },
    data() {
      return {
        logging: false,
        pageStatus: '登录',
        resendStatus: false,
        error: '',
        form: this.$form.createForm(this),
        forgetMsg: '获取验证码',
        disabledCodeBtn: false,
        regMsg: '获取验证码',
        disabledReg: false,
        forgetForm: {
          tel: '',  // 手机号
          phoneCode: '', // 验证码
          password: '' // 新密码
        },
        regForm: {
          tel: '',  // 手机号
          phoneCode: '',  // 验证码
          username: '', // 用户名
          password: '', // 密码
          checkpassword: '', // 密码
        }
      }
    },
    computed: {
      systemName() {
        return this.$store.state.setting.systemName
      }
    },
    methods: {
      ...mapMutations('account', ['setUser', 'setPermissions', 'setRoles']),
      onSubmit(e) {
        e.preventDefault()
        this.form.validateFields((err) => {
          if (!err) {
            this.logging = true
            const name = this.form.getFieldValue('name')
            const password = this.form.getFieldValue('password')
            let formData = new FormData()
            formData.append('username', name)
            formData.append('password', password)
            login(formData).then((res) => {
              if(res.data.code == 200) {
                res.data.result.expireAt = new Date(new Date().getTime() + 30 * 60 * 10000)
                let result = {
                  code: res.data.code,
                  isAdmin:res.data.result.isAdmin,
                  data: {
                    user: { 
                      name: res.data.result.username,
                      avatar: 'https://gw.alipayobjects.com/zos/rmsportal/cnrhVkzwxjPwAaCfPbdc.png',
                      userId: res.data.result.userId,
                      userInfo: res.data.result.userInfo,
                      uPath: res.data.result.uPath
                    },
                    permissions: [{id: res.data.result.isAdmin, operation: ['add', 'edit']}],
                    roles: [{id: 'admin', operation: ['add', 'edit', 'delete']}],
                    token: res.data.result.token,
                    expireAt: new Date(new Date().getTime() + 30 * 60 * 10000)
                  }
                }
                this.afterLogin(result)
              } else {
                this.$message.warning(res.data.result, 6)
                this.logging = false
              }

            })
            .catch((res) => {
              this.$message.warning(res.data.result)
              this.logging = false
            })
          }
        })
      },
      afterLogin(res) {
        this.logging = false
        const loginRes = res
        console.log('----------',loginRes.data);
        if (loginRes.code >= 0) {
          const {
            user,
            permissions,
            isAdmin,
            roles
          } = loginRes.data
          this.setUser(user)
          this.setPermissions(permissions)
          this.setRoles(roles)
          setAuthorization({
            token: loginRes.data.token,
            expireAt: new Date(loginRes.data.expireAt)
          })
          // 获取路由配置
          let result = {}
          result.code = 0
          result.data = [{
            router: 'root',
            children: []
          }]
          const routesConfig = result.data
          loadRoutes(routesConfig)
          this.$router.push('/main')
          // this.$message.success(loginRes.message, 3)
        } else {
          this.error = loginRes.message
        }
      },
      onClose() {
        this.error = false
      },
    /**
     * @desc 获取验证码
     */
      getCode(from) {
        let _this = this
        let obj = {
          '注册': '1',
          '修改密码': '2',
        }
        let formData = new FormData()
        formData.append('type', obj[from])
        if (from == '修改密码') {
          formData.append('phone', this.forgetForm.tel)
        } else {
          formData.append('phone', this.regForm.tel)
        }
        getPhoneCode(formData).then((res) => {
          if(from == '修改密码') {
            _this.setForget(60)
          } else if(from == '注册') {
            _this.setReg(60)
          }
        })
      },
      /**
       * @desc 设置忘记密码
       */
      setForget(time) {
        if (time === 0) {
          this.disabledCodeBtn = false
          this.forgetMsg = "获取验证码"
          return
        } else {
          this.disabledCodeBtn = true;
          this.forgetMsg = `重新发送(${time})`
          time--
        }
        setTimeout(()=> {
          this.setForget(time)
        }, 1000)
      },
      /**
       * @desc 设置注册
       */
      setReg(time) {
        if (time === 0) {
          this.disabledReg = false
          this.regMsg = "获取验证码"
          return
        } else {
          this.disabledReg = true;
          this.regMsg = `重新发送(${time})`
          time--
        }
        setTimeout(()=> {
          this.setReg(time)
        }, 1000)
      },
      /**
       * @desc 重置
       */
      resend() {
        let formData = new FormData()
        this.resendStatus = true
        formData.append('phone', this.forgetForm.tel)
        formData.append('phoneCode', this.forgetForm.phoneCode)
        formData.append('password', this.forgetForm.password)
        updatePwd(formData).then((res) => {
          if(res.data.code == 200) {
              this.$message.success(res.data.result)
              this.resendStatus = false
              this.pageStatus = '登录'
          } else {
              this.resendStatus = false
              this.$message.error(res.data.result)
          }
        })
      },
      /**
       * @desc 注册
       */
      toRegister() {
        if(this.regForm.checkpassword !== this.regForm.password) {
          this.$message.error('两次密码不一致')
          return false
        } else {
          let formData = new FormData()
          formData.append('phone', this.regForm.tel)
          formData.append('phoneCode', this.regForm.phoneCode)
          formData.append('username', this.regForm.username)
          formData.append('password', this.regForm.password)
          register(formData).then((res) => {
            if (res.data.code == 200) {
              this.$message.success(res.data.result)
              this.pageStatus = '登录'
            } else {
              this.$message.error(res.data.result)
            }
          })
        }
      },
    }
  }
</script>

<style lang="less" scoped>
  .common-layout {
    .top {
      text-align: center;

      .header {
        height: 44px;
        line-height: 44px;

        a {
          text-decoration: none;
        }

        .logo {
          height: 44px;
          vertical-align: top;
          margin-right: 16px;
        }

        .title {
          font-size: 33px;
          color: @title-color;
          font-family: 'Myriad Pro', 'Helvetica Neue', Arial, Helvetica, sans-serif;
          font-weight: 600;
          position: relative;
          top: 2px;
        }
      }

      .desc {
        font-size: 14px;
        color: @text-color-second;
        margin-top: 12px;
        margin-bottom: 40px;
      }
    }

    .loginBox {
      width: 420px;
      margin: 20px auto;
      border-radius: 25px;
      padding: 24px;
      background-color: #fff;
    }

    .login {
      width: 368px;
      margin: 0 auto;

      @media screen and (max-width: 576px) {
        width: 95%;
      }

      @media screen and (max-width: 320px) {
        .captcha-button {
          font-size: 14px;
        }
      }

      .icon {
        font-size: 24px;
        color: @text-color-second;
        margin-left: 16px;
        vertical-align: middle;
        cursor: pointer;
        transition: color 0.3s;

        &:hover {
          color: @primary-color;
        }
      }
    }
  }
</style>